<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @add="addFn" :list="list" @checkAll="checkAll"></TodoHeader>
    <TodoMain :list="showlist" @del="delFn" @change="changeFn"></TodoMain>
    <TodoFooter
      :list="list"
      @clear="clearFn"
      :type="type"
      @changeType="changeTypeFn"
    >
    </TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

export default {
  components: {
    TodoFooter,
    TodoHeader,
    TodoMain,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todolist')) ||[],
      type: 'all',
    }
  },
  methods: {
    //删除功能，filter筛选
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    addFn(task) {
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 1, //判断数据如果有就在最后一个数据的id基础上加1，没有则默认为1
        name: task,
        isDone: false,
      })
    },
    checkAll(val) {
      this.list.forEach((item) => (item.isDone = val))
    },
    changeFn(id) {
      // 修改状态
      const res = this.list.find((item) => item.id == id)
      res.isDone = !res.isDone
    },
    clearFn() {
      // 当为true可以清除
      this.list = this.list.filter((item) => item.isDone == false)
    },
    changeTypeFn(type) {
      this.type = type
    },
  },
  computed: {
    showlist() {
      if (this.type === 'yes') {//显示已完成
        return this.list.filter((item) => item.isDone)
      } else if (this.type === 'no') {//显示未完成
        return this.list.filter((item) => !item.isDone)
      } else {
        return this.list//全部显示
      }
    },
  },
  watch:{
    list:{
      deep:true,
      handler(newval){
        //本地存储
        localStorage.setItem('todolist',JSON.stringify(newval))
      }
    }
  }
}
</script>
